package com.hippoframework.mvc;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hippoframework.bean.ApplicationContext;
import com.hippoframework.bean.aware.ApplicationContextAware;
import com.hippoframework.utils.ApplicationContextUtils;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * Servlet请求分发入口
 *
 * @author TylerW
 * @date 3/26/2020 4:29 PM
 */
@WebServlet(name = "dispatcherServlet")
@Slf4j
public class DispatcherServlet extends HttpServlet implements ApplicationContextAware {

    private Map<String, Handler> requestHandlerMap = new HashMap<>();

    @Setter
    private ApplicationContext applicationContext;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp, HttpMethod.GET);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp, HttpMethod.POST);
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp, HttpMethod.PUT);
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp, HttpMethod.DELETE);
    }

    /**
     * HttpRequest 实际分发中心
     *
     * @param req  HttpServletRequest
     * @param resp HttpServletResponse
     */
    protected void processRequest(HttpServletRequest req, HttpServletResponse resp, HttpMethod method) throws ServletException, IOException {
        log.info("processRequest");
    }

    @Override
    public void init() throws ServletException {
        System.out.println("==========servlet init=====");
        setApplicationContext(ApplicationContextUtils.getApplicationContext());
    }
}
